﻿using ACC.Business;
using ACC.Business.Process;
using ACC.Data;
using ACC.Data.ACCLog;
using ACC.Data.Comm;
using ACC.Data.Line;
using ACC.Device;
using ACC.Device.PLC.Siemens;
using System;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using ACC.Business.Stn;
using ACC.Interface.Extensions;
using ACC.LineDevice.KukaPack;

namespace Script
{
    /// <summary>
    /// 模组缓存
    /// 校验电芯批次
    /// </summary>
    public class L1M04071 : StnProcessKukaPack
    {
        string[] modules = new string[3];
        int Days = 7; // 电芯批次不能合批条件，7天内不同批
        public L1M04071(StnRunningData data)
            : base(data)
        {
            IsReport = false;
            IsACCReport = false;
            IsPalletRelationSN = false;
        }

        protected override void CreateBusinessLogic()
        {
            base.CreateBusinessLogic();
            _loadProcess = new LoadProcess_L1M04070Ex(_data);
        }
        protected override ACCDevice CreateDevice()
        {

            ACCDevice dev = base.CreateDevice();
            if (kukaSiemensDev != null)
            {
                kukaSiemensDev.DB190 = 800;
                kukaSiemensDev.DB190_Offset = 20000;
                kukaSiemensDev.DB192 = 80;
                kukaSiemensDev.DB192_PLC_Offset = 20066;
                kukaSiemensDev.DB193 = 800;
                kukaSiemensDev.DB193_PLC_Offset = 20034;
                kukaSiemensDev.DB193_ACC_Offset = 20068;
                kukaSiemensDev.DB194 = 800;
                kukaSiemensDev.DB194_PLC_Offset = 20034;
                kukaSiemensDev.DB194_PLC_Data_Offset = 20078;

                kukaSiemensDev.LoadBarcodeCount = 3;
            }

            return dev;
        }

        public override ACCCode ReadLoadParam(ACCDevice dev, out ACCDevice.LoadParam param)
        {
            modules[0] = modules[1] = modules[2] = string.Empty;

            ACCCode rs = base.ReadLoadParam(dev, out param);
            if(rs == ACCCode.ACCOK)
            {
                if (!string.IsNullOrEmpty(param.UnitSN) &&
                param.ComponentSN.Length > 1 && !string.IsNullOrEmpty(param.ComponentSN[0]) && !string.IsNullOrEmpty(param.ComponentSN[1]))
                {
                    bool hasA = false, hasB = false, hasC = false;
                    var sns = this.GetPallet(param.UnitSN);
                    modules[0] = sns == null || sns.Count() < 1 ? string.Empty : sns[0];
                    if (!string.IsNullOrEmpty(modules[0]) && modules[0].Length > 9)
                    {
                        string pos = modules[0].Substring(8, 1);
                        if (pos == "A") hasA = true;
                        else if (pos == "B") hasB = true;
                        else if (pos == "C") hasC = true;
                    }
                    sns = this.GetPallet(param.ComponentSN[0]);
                    modules[1] = sns == null || sns.Count() < 1 ? string.Empty : sns[0];
                    if (!string.IsNullOrEmpty(modules[1]) && modules[1].Length > 9)
                    {
                        string pos = modules[1].Substring(8, 1);
                        if (pos == "A") hasA = true;
                        else if (pos == "B") hasB = true;
                        else if (pos == "C") hasC = true;
                    }
                    sns = this.GetPallet(param.ComponentSN[1]);
                    modules[2] = sns == null || sns.Count() < 1 ? string.Empty : sns[0];
                    if (!string.IsNullOrEmpty(modules[2]) && modules[2].Length > 9)
                    {
                        string pos = modules[2].Substring(8, 1);
                        if (pos == "A") hasA = true;
                        else if (pos == "B") hasB = true;
                        else if (pos == "C") hasC = true;
                    }

                    if(!hasA || !hasB || !hasC)
                    {
                        return rs = ACCCode.UserDef_130; // 模组匹对失败
                    }

                    param.ComponentSN = new string[] { };
                }
                else
                {
                    rs = ACCCode.Unit_Barcode_Empty;
                }
            }

            return rs;
        }


        public override ACCCode SendLoadResult(ACCDevice dev, ACCDevice.LoadResult result)
        {
            if (result.ErrorCode == ACCCode.ACCOK)
            {
                List<string> lots = new List<string>();
                List<DateTime> lotDts = new List<DateTime>();
                //LineData jtLineData = LineManager.LineDatas["PL02_JT"];
                foreach (string module in modules)
                {
                    string lot = GetLotNo(module);
                    //var mzUnit = UnitDataProcess.GetWIPUnit(_lineData, module);
                    //if (mzUnit == null) continue;
                    //var jtUnitID = mzUnit.GetUnitIDByIDName("模组基体");
                    //if (jtUnitID == null) continue;
                    //var jtUnit = UnitDataProcess.GetWIPUnit(jtLineData, jtUnitID.IDValue);
                    //if (jtUnit == null) continue;
                    //WIPUnitID dxUnitID = jtUnit.GetUnitIDByIDName("电芯");
                    //if (dxUnitID == null) continue;
                    //string lot = string.Empty;
                    //logger.Debug("dxUnitID=" + dxUnitID == null ? "空" : "OK");
                    //logger.Debug("battary=" + dxUnitID.IDValue);
                    //lot = GetBatteryLot(dxUnitID.IDValue);
                    lots.Add(lot);
                    lotDts.Add(GetLotDateTimeFromBatteryLot(lot));
                    //logger.Debug("lot=" + lot);
                    if (string.IsNullOrEmpty(lot))
                    {
                        lots.Add(string.Empty);
                        lotDts.Add(DateTime.MinValue);
                        result.ErrorCode = ACCCode.UserDef_126; // 电芯批次为空
                        result.ErrorMsg = string.Format("模组{0}的电芯批次为空", module);
                    }
                }

                if (result.ErrorCode == ACCCode.ACCOK && Days >= 0)
                {
                    var max = lotDts.Count > 0 ? lotDts.Max() : DateTime.MaxValue;
                    var min = lotDts.Count > 0 ? lotDts.Min() : DateTime.MinValue;
                    if ((max - min).Days > Days)
                    {
                        result.ErrorCode = ACCCode.UserDef_127; // 电芯不能合批，电芯批次日期相差超过7天
                        result.ErrorMsg = string.Format("电芯不能合批，电芯批次日期相差超过{0}天", Days);
                    }
                }
            }

            return base.SendLoadResult(dev, result);
        }

        /// <summary>
        /// 根据电芯批次码获取批次日期
        /// </summary>
        /// <param name="lot"></param>
        /// <returns></returns>
        DateTime GetLotDateTimeFromBatteryLot(string lot)
        {
            try
            {
                if (lot.Length > 8)
                {
                    string d = lot.Substring(lot.Length - 8, 4);
                    int year = int.Parse(d.Substring(0, 1));
                    DateTime now = DateTime.Now;
                    if (year > now.Year)
                        year = now.Year - now.Year % 10 - 10 + year;
                    else
                        year = now.Year - now.Year % 10 + year;
                    string month = d.Substring(1, 1);
                    if (month == "J") month = "11";
                    if (month == "Q") month = "12";
                    int day = int.Parse(d.Substring(2, 2));
                    return new DateTime(year, int.Parse(month), day);
                }
            }
            catch { }

            return DateTime.MinValue;
        }


        /// <summary>
        /// 通过模组内部码，先找关联的基体码，然后找基体码绑定电芯的批次号
        /// </summary>
        /// <param name="UNITSN"></param>
        /// <returns></returns>
        public string GetLotNo(string UNITSN)
        {
            string vs = "";
            string sql = string.Format("SELECT DISTINCT LOTNO FROM [ACC_BATTERY_DATA] WHERE BARCODE IN ( SELECT ID_VALUE FROM [ACC_UNITID]  WHERE LINE = 'PL02_JT' AND ID_NAME = '电芯' AND UNITSN IN (SELECT ID_VALUE FROM [DBO].[ACC_UNITID] WHERE   LINE = 'PL02_MZ' AND ID_NAME = '模组基体' AND UNITSN = '{0}'))", UNITSN);
            DataTable dt = DataManager.DBHelper.Query(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                vs = dt.Rows[0]["LOTNO"].ToString();
            }
            return vs;
        }
    }

    public class LoadProcess_L1M04070Ex : LoadProcess
    {
        public LoadProcess_L1M04070Ex(StnRunningData data)
            : base(data)
        {

        }
        /// <summary>
        ///不需要进行load业务的处理
        /// </summary>
        /// <param name="dev"></param>
        public override void ProcessLoad(ACCDevice dev)
        {

        }
    }

    public class UnloadProcess_L1M04070Ex : UnloadProcess
    {
        public UnloadProcess_L1M04070Ex(StnRunningData data)
            : base(data)
        {
        }

        public override void ProcessUnload(ACC.Device.ACCDevice dev)
        {

        }
    }
}